package com.xyz.frame.api.controller.shzhyun;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.*;

/**
 * server sent event 长连接对话接口
 */
@RestController
@RequestMapping("/sse")
@Slf4j
public class ChatController {

    private final List<SseEmitter> emitters = new CopyOnWriteArrayList<>();
    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    // SSE 连接端点
    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter handleSse() {
        SseEmitter emitter = new SseEmitter(60_000L);
        emitters.add(emitter);
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        scheduler.scheduleAtFixedRate(() -> {
            try {
                // 发送心跳
                emitter.send(SseEmitter.event().comment("heartbeat"));
            } catch (IOException e) {
                scheduler.shutdown(); // 关闭调度器
            }
            // 每 30 秒发送一次心跳
        }, 0, 30, TimeUnit.SECONDS);

        // 移除已关闭的连接
        emitter.onCompletion(() -> emitters.remove(emitter));
        emitter.onTimeout(() -> emitters.remove(emitter));
        emitter.onError((ex) -> {emitters.remove(emitter);log.error(ex.getMessage());});

        return emitter;
    }

    // 接收用户消息的端点
    @PostMapping("/send")
    public void sendMessage(@RequestParam String message) {
        executor.execute(() -> {
            for (SseEmitter emitter : emitters) {
                try {
                    emitter.send(SseEmitter.event().data(message, MediaType.TEXT_PLAIN));
                } catch (IOException e) {
                    emitter.completeWithError(e);
                }
            }
        });
    }
}
